import React from 'react';
import { Button, message } from 'antd';
import ProForm, { ModalForm, ProFormText, ProFormCascader } from '@ant-design/pro-form';
import { pinyin } from 'pinyin-pro';

import { request } from 'umi';
import { api } from '@/global';
import Item from 'antd/lib/list/Item';

const randomSalt = (n = 1): number => {
  const max = Math.pow(10, n) - 1;
  const min = Math.pow(10, n - 1);
  return Math.round(Math.random() * (max - min)) + min;
};

type folderType = {
  bucketName: string;
  children: string;
  id: number;
  parent: number;
  pathCode: string;
  pathName: string;
  childrenList: folderType[];
};

const generateNode: any = (item: folderType) => {
  if (!item) {
    return;
  }

  const result = {
    value: item.id,
    label: item.pathName,
  };
  if (item.childrenList) {
    result['children'] = item.childrenList.map((i) => {
      return generateNode(i);
    });
  }

  return result;
};

type requestType = {
  parentId: any[];
  pathName: string;
};

export default (props: any) => {
  return (
    <ModalForm<{
      name: string;
      company: string;
    }>
      title="新建"
      trigger={<a>新建文件夹</a>}
      autoFocusFirstInput
      modalProps={{
        onCancel: () => console.log('run'),
      }}
      onFinish={async (r: requestType) => {
        if (r.pathName && r.pathName.charAt(r.pathName.length - 1) === '/') {
          message.error('文件末尾请勿以 / 结尾');
          return;
        }

        const py_temp = pinyin(r.pathName, {
          toneType: 'none',
          type: 'array',
          removeNonZh: true,
        });
        let py = py_temp.join('');
        py += randomSalt(3);
        py += '/';

        let parent = 0;
        if (typeof r.parentId[r.parentId.length - 1] == 'number') {
          parent = r.parentId[r.parentId.length - 1];
        }

        const bucketInfo = await request(api.getBucketInfo);

        const bid = bucketInfo.data.filter((item) => item.bucketName === r.parentId[0]);

        const result = await request(api.createFileFolder, {
          method: 'POST',
          data: {
            pathName: r.pathName,
            parent,
            pathCode: py,
            bucketId: bid && bid[0].id,
          },
        });

        if (result.success) {
          message.info('新增成功');
          props?.reloadData();
        } else {
          message.info('添加失败');
        }
        return true;
      }}
    >
      <ProForm.Group>
        <ProFormText
          width="md"
          name="pathName"
          label="文件夹名称"
          placeholder="请输入文件夹名称"
          rules={[
            {
              required: true,
              message: '请输入文件夹名称',
            },
          ]}
        />
      </ProForm.Group>
      <ProForm.Group>
        <ProFormCascader
          name="parentId"
          width="md"
          label="需要创建的父级文件夹"
          fieldProps={{
            changeOnSelect: true,
          }}
          rules={[
            {
              required: true,
              message: '请选择文件筒',
            },
          ]}
          request={async () => {
            const result = await request(api.getFolderList);

            const data: folderType = result.data;
            const alist: any[] = [];

            Object.keys(data).map((item, index) => {
              alist.push({
                value: item,
                label: item,
                children: data[item].map((c: folderType) => {
                  return generateNode(c);
                }),
              });
            });

            const bucketName = await request(api.getBucketInfo);

            bucketName.data.map((i) => {
              let flag = false;

              alist.forEach((r) => {
                if (r.value === i.bucketName) {
                  flag = true;
                }
              });

              if (!flag) {
                alist.push({
                  value: i.bucketName,
                  label: i.bucketName,
                });
              }
            });

            return alist;
          }}
        />
      </ProForm.Group>
    </ModalForm>
  );
};
